// page/component/new-pages/cart/cart.js
Page({
  data: {
    carts: [],                      // 购物车物品列表
    hasList: false,          // 列表是否有数据
    totalPrice: 0,           // 总价，初始为0
    selectAllStatus: false,    // 全选状态，默认全选
    recommends: [],
    userID: null
  },
  
  onShow() {
    this.setData({ 
      number: 0,
      selectAllStatus: false
    });
    // this.getTotalPrice();
    let that = this;
    console.log(this.data);
    wx.request({
      url: 'https://localhost:80/goods/hot/1/goods',
      header: {
        'content-type': 'application/json'
      },
      success (res) { 
        console.log(res);
        for (let i = 0; i < res.data.list.length; i++)
        {
          let arr = [];
          let str = res.data.list[i].goods.goodsImg;
          arr = str.split(',');
          console.log(arr);
          res.data.list[i].goods.goodsImg = arr;
        }
        that.setData({
          recommends: res.data.list
        })
        console.log(that.data.recommends[0].goods);
        console.log("-----------------------------");
      }
    });
    wx.getStorage({
      key: 'userID',
      success(res) {
        that.setData({
          userID: res.data
        }) 
      }
    });
    let userId = this.data.userID;
    if (userId == null) {
      userId = getApp().globalData.userID
    } 
    console.log(userId);
    wx.request({
      // url: 'https://www.zhaoshenma.cn:80/cart/'+ userId +'/query',
      url: 'https://localhost:80/cart/'+ userId +'/query',
      header: {
        'content-type': 'application/json'
      },
      success (res) { 
        console.log('===================================');
        console.log(res);
        console.log(Object.values(res.data));
        res.data.rows = Object.values(res.data);
        console.log('===================================');
        let isList = null;
        if (res.data.rows.length == 0) {
          isList = false;
        } else {
          isList = true;
        }
        for (let i = 0; i < res.data.rows.length; i++)
        {
          res.data.rows[i].selected = false;
          let arr = [];
          let str = res.data.rows[i].cartGoods.goodsImg;
          arr = str.split(',');
          console.log(arr);
          res.data.rows[i].cartGoods.goodsImg = arr[0];
          res.data.rows[i].cartPrice = res.data.rows[i].cartPrice / res.data.rows[i].cartNum;
          res.data.rows[i].cartPrice = res.data.rows[i].cartPrice.toFixed(2);
          console.log(res.data.rows[i].cartPrice);       
        }
        that.setData({
          carts: res.data.rows,
          hasList: isList
        })
        console.log('ok');
        console.log('-------------------------------');
        that.getTotalPrice();
        console.log('-------------------------------');
      }  
    });
  },
  
  selectList(e) {
    const index = e.currentTarget.dataset.index;
    let selectSure;
    let lengths = 0;
    let allSelected;
    for (let i = 0; i < this.data.carts.length; i++)
    {
      if (this.data.carts[i].selected) {
        lengths++;
      }
    }
    if (lengths == this.data.carts.length - 1) {
      if (this.data.carts[index].selected) {
        allSelected = false;
      } else {
        allSelected = true;
      }
    } else {
      allSelected = false;
    }
    if (!this.data.carts[index].selected) {
      selectSure = 1;
    } else {
      selectSure = -1;
    }
    let carts = this.data.carts;
    const selected = carts[index].selected;
    carts[index].selected = !selected;
    this.setData({
      carts: carts,
      number: this.data.number + selectSure,
      selectAllStatus: allSelected
    });
    this.getTotalPrice();
  },

  deleteList(e) {
    let that = this;
    const index = e.currentTarget.dataset.index;
    let cartId = this.data.carts[index].cartGoods.goodsId;
    let selectSure;
    let allSelected = true;
    let carts = this.data.carts;
    if (this.data.carts[index].selected) {
      selectSure = -1
    } else {
      selectSure = 0
    }
    carts.splice(index, 1);
    this.setData({
      carts: carts
    })
    console.log(this.data.carts);
    console.log()
    for (let i = 0; i < this.data.carts.length; i++)
    {
      if (!this.data.carts[i].selected) {
        allSelected = false;
      }
    }
    if (this.data.carts.length == 0) {
      allSelected = false;
    }     
    this.setData({
      number: this.data.number + selectSure,
      selectAllStatus: allSelected
    });
    if(!carts.length){
      this.setData({
        hasList: false
      });
      this.getTotalPrice();
    }else{
      this.getTotalPrice();
    }
    wx.getStorage({
      key: 'userID',
      success(res) {
        that.setData({
          userID: res.data
        }) 
      }
    });
    let userId = this.data.userID;
    if (userId == null) {
      userId = getApp().globalData.userID
    } 
    let Url = 'https://localhost:80/cart/delete/' + cartId + '/' + userId;
    wx.request({
      url: Url,
      method: 'delete',
      header: {
        'content-type': 'application/json'
      },
      success (res) {
        console.log(res);
        wx.showToast({
          title: '删除成功',
          icon: 'success',
          duration: 2000
        })
      },
      fail (res) {
        console.log(res);
        wx.showToast({
          title: '删除失败',  
          icon: 'none',
          duration: 2000
        })
      }
    })
  },

  selectAll(e) {
    let selectAllStatus = this.data.selectAllStatus;
    selectAllStatus = !selectAllStatus;
    let carts = this.data.carts;
    let lengths;
    for (let i = 0; i < carts.length; i++) {
      carts[i].selected = selectAllStatus;
    }
    if (this.data.carts.length == 0) {
      lengths = 0
    } else {
      if (this.data.carts[0].selected) {
        lengths = this.data.carts.length
      } else {
        lengths = 0
      }
    }
    this.setData({
      selectAllStatus: selectAllStatus,
      carts: carts,
      number: lengths
    });
    this.getTotalPrice();
  },

  addCount(e) {
    const index = e.currentTarget.dataset.index;
    let carts = this.data.carts;
    let num = carts[index].cartNum;
    num = num + 1;
    carts[index].cartNum = num;
    this.setData({
      carts: carts
    });
    this.getTotalPrice();
  },

  minusCount(e) {
    const index = e.currentTarget.dataset.index;
    const obj = e.currentTarget.dataset.obj;
    let carts = this.data.carts;
    let num = carts[index].cartNum;
    if(num < 2){
      return false;
    }
    num = num - 1;
    carts[index].cartNum = num;
    this.setData({
      carts: carts
    });
    this.getTotalPrice();
  },

  getTotalPrice() {
    let carts = this.data.carts;                  // 获取购物车列表
    console.log(carts);
    console.log('---------------------------------------------------------------------------');
    let total = 0;
    for(let i = 0; i<carts.length; i++) {         // 循环列表得到每个数据
      if(carts[i].selected) {                     // 判断选中才会计算价格
        total += carts[i].cartNum * carts[i].cartPrice;   // 所有价格加起来
      }
      console.log(carts[i].cartNum);
      console.log(carts[i].cartPrice);
      console.log(total);
    }
    console.log('---------------------------------------------------------------------------');
    console.log(total);
    this.setData({                                // 最后赋值到data中渲染到页面
      carts: carts,
      totalPrice: total.toFixed(2)
    });
  },

  toBuy () {
    function Details (detailNum, detailPrice, detailGoods) {
      this.detailNum = detailNum;
      this.detailPrice = detailPrice;
      this.detailGoods = detailGoods;
    }
    let goodsImg = [];
    let orders = [];
    let n = 0;
    let order = [];
    console.log(this.data.carts)
    console.log(order);
    console.log(orders);
    for (let i = 0; i < this.data.carts.length; i++)
    {
      if (this.data.carts[i].selected) {
        console.log(this.data.carts[i].selected);
        goodsImg[i] = this.data.carts[i].cartGoods.goodsImg;
        console.log(this.data.carts[i].cartGoods.goodsImg);
        let detailNum = this.data.carts[i].cartNum;
        let detailPrice = this.data.carts[i].cartPrice * this.data.carts[i].cartNum;
        detailPrice = detailPrice.toFixed(2);
        let detailGoods = this.data.carts[i].cartGoods.goodsId;
        orders[i] = new Details(detailNum, detailPrice, detailGoods);
        console.log(orders);
      }
    }
    order = JSON.stringify(orders);
    console.log(order);
    console.log(orders.length);
    if (orders.length === 0) {
      wx.showModal({
        title: '亲，先选好物品，再支付吧',
        success(res) {
          console.log('用户未选择物品')
        }
      })
    } else {
      wx.setStorage({
        key: 'details',
        data: order
      })
      wx.setStorage({
        key: 'price',
        data: this.data.totalPrice
      })
      wx.setStorage({
        key: 'imgs',
        data: goodsImg
      })
      wx.navigateTo({
        url: '../orders/orders?order=' + JSON.stringify(order) + '&price=' + JSON.stringify(this.data.totalPrice) + '&imgs=' + JSON.stringify(goodsImg)
      })
      console.log(this.data.totalPrice);
    }
  },

  details (e) {
    let goodsId = e.currentTarget.dataset.id;
    console.log(goodsId);
    wx.navigateTo({
      url: '../details/details?goodsId=' + goodsId
    })
  }
})

